package tmt.usercenter.web.common;

import com.tmt.annotation.ScopeDescriptor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotationUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Utils {

	/**
	 * 获取当前电脑名称
	 *
	 * @return 电脑名称
	 */
	public static String hostName() {
		String hostname = "Unknown";
		try {
			InetAddress addr = InetAddress.getLocalHost();
			hostname = addr.getHostName();
		} catch (UnknownHostException e) {
			System.out.println("Hostname can not be resolved. ");
		}
		return hostname;
	}

	public static String clientName(HttpServletRequest request) {
		String computerName = null;
		String remoteAddress = request.getRemoteAddr();
		try {
			InetAddress inetAddress = InetAddress.getByName(remoteAddress);
			computerName = inetAddress.getHostName();
			if (computerName.equalsIgnoreCase("localhost")) {
				computerName = java.net.InetAddress.getLocalHost().getCanonicalHostName();
			}
		} catch (UnknownHostException e) {
			System.out.println("Hostname can not be resolved. ");
		}
		if (StringUtils.trim(computerName).length() > 0) computerName = computerName.toUpperCase();
		System.out.println("computerName: " + computerName);
		return computerName;
	}

	public static List<ScopeDescriptor> getAllScopes(ApplicationContext applicationContext) {
		Map<String, Object> map = applicationContext.getBeansWithAnnotation(ScopeDescriptor.class);
		return map.values().stream().map(c -> AnnotationUtils.findAnnotation(c.getClass(), ScopeDescriptor.class)).collect(Collectors.toList());
	}
}
